package com.pro.control;

import com.pro.entity.JsonData;
import com.pro.entity.User;
import com.pro.service.UserService;
import com.pro.utils.MD5Util;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @ClassName: UserController
 * @Author: 笑笑
 * @DATE: 2021/11/6
 * @TIME: 下午 03:13
 */
@RestController
@RequestMapping("/User")
public class UserController {

    @Autowired(required = true)
    private UserService userService;

    @Autowired(required = true)
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired(required = true)
    private TransactionDefinition transactionDefinition;
    //根据用户名查询用户
    @RequestMapping("/getByName")
    public JsonData getByName(String createName) {
        Integer byName = userService.getByName(createName);
        return byName != null ? JsonData.buildSuccess(byName) : JsonData.buildError("服务器错误");
    }

    //根据用户id修改用户信息
    //刘
    @RequestMapping("/updateUser")
    public JsonData updateUser(User user){
        Boolean aBoolean = userService.updateUser(user);
        return aBoolean != null ? JsonData.buildSuccess(aBoolean) : JsonData.buildError("服务器错误");
    }

    //查询所有的用户
    @RequestMapping("/getAllUser")
    public JsonData getAllUser(User user) {
        List<User> userList = userService.getAllUser(user);
        return userList != null ? JsonData.buildSuccess(userList) : JsonData.buildError("服务器错误");
    }

    //根据id查询用户
    @RequestMapping("/getById")
    public JsonData getById(Integer id) {
        User user = null;
        try {
            user = userService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user != null ? JsonData.buildSuccess(user) : JsonData.buildError("服务器错误");
    }

    //添加一个用户
    @RequestMapping("/addUser")
    public JsonData addUser(HttpServletRequest request, User user) {
        String userIpAddr = request.getRemoteAddr();
        user.setPassword(MD5Util.md5(user.getPassword()));
        user.setRegisterIp(userIpAddr);
        Boolean b = userService.addUser(user);
        return b ? JsonData.buildSuccess(b) : JsonData.buildError("服务器错误");
    }

    //导入用户
    @Transactional
    @RequestMapping("importUser")
    public JsonData importUser(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建实体类
        User user = new User();

        //根据指定的文件输入流导入Excel从而产生Workbook对象
        Workbook wb0 = null;
        try {
            wb0 = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取Excel文档中的第一个表单
        Sheet sht0 = wb0.getSheetAt(0);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Boolean b = null;
        //对Sheet中的每一行进行迭代
        for (Row r : sht0) {
            //如果当前行的行号（从0开始）未达到2（第三行）则从新循环
            if (r.getRowNum() < 2){
                continue;
            }
            //取出当前行第1个单元格数据，并封装在info实体stuName属性上
            user.setTrueName(r.getCell(0).getStringCellValue());
            user.setSex(r.getCell(1).getStringCellValue());
            user.setAccount(String.valueOf(r.getCell(2).getNumericCellValue()));
            user.setAcatarUrl(r.getCell(3).getStringCellValue());
            user.setEmail(String.valueOf(r.getCell(4).getNumericCellValue()));
            user.setPassword(MD5Util.md5(String.valueOf(r.getCell(5).getNumericCellValue())));
            user.setRemark(r.getCell(6).getStringCellValue());
            user.setEnabled((int) r.getCell(7).getNumericCellValue());
            user.setPhone(String.valueOf(r.getCell(8).getNumericCellValue()));
            user.setIdCard(String.valueOf(r.getCell(9).getNumericCellValue()));
            user.setBirthDate(String.valueOf(simpleDateFormat.format(r.getCell(10).getDateCellValue())));
            user.setDeptId((int) r.getCell(11).getNumericCellValue());
            user.setFreestyle(r.getCell(12).getStringCellValue());
            user.setRegisterDate(String.valueOf(simpleDateFormat.format(r.getCell(13).getDateCellValue())));
            user.setRegisterIp(String.valueOf(r.getCell(14).getStringCellValue()));
            user.setStatus((int) r.getCell(15).getNumericCellValue());
            user.setGrade((int) r.getCell(16).getNumericCellValue());
            user.setWages((int) r.getCell(17).getNumericCellValue());

            b = userService.addUser(user);
        }

        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonData.buildSuccess(b);
    }
}
